﻿package  {
	
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
	import flash.events.MouseEvent;
	import flash.events.KeyboardEvent;
	import flash.events.Event;
	
	public class XButton extends MovieClip {
		
		public var actor:SimpleButton;
		public var states:MovieClip;
		public var buttonText:String;
		public var keys:Array;
		
		//events
		public var onMouseOver:Function;
		public var onMouseOut:Function;
		public var onMousePress:Function;
		public var onMouseRelease:Function;
		
		public function XButton() {
			super();
			this.addEventListener(Event.ADDED_TO_STAGE, hOnStage);
		}
		
		public function hOnStage(e:Event):void
		{
			this.removeEventListener(Event.ADDED_TO_STAGE, hOnStage);
			this.actor.addEventListener(MouseEvent.MOUSE_OVER, this.hOver);
			this.actor.addEventListener(MouseEvent.MOUSE_OUT, this.hOut);
			this.actor.addEventListener(MouseEvent.MOUSE_DOWN, this.hPress);
			this.actor.addEventListener(MouseEvent.CLICK, this.hRelease);
			this.stage.addEventListener(KeyboardEvent.KEY_DOWN, this.hKeyboard);
			this.states.addFrameScript(1, this.updateText);
			this.states.addFrameScript(2, this.updateText);
			this.states.addFrameScript(3, this.updateText);
			this.states.addFrameScript(4, this.updateText);
			this.setActive(this.actor.enabled);
		}
		
		public function setActive(val:Boolean):void
		{
			this.actor.enabled = val;
			this.actor.visible = val;
			this.states.gotoAndStop(val ? 2 : 1);
		}
		
		private function hOver(e:MouseEvent):void
		{
			if( this.actor.enabled )
			{
				this.states.gotoAndStop(3);
				//callEvent;
				if(this.onMouseOver)
					this.onMouseOver();
			}
			
		}
		private function hOut(e:MouseEvent):void
		{
			if( this.actor.enabled )
			{
				this.states.gotoAndStop(2);
				//callEvent
				if(this.onMouseOut)
					this.onMouseOut();
			}
		}
		private function hPress(e:MouseEvent):void
		{
			if( this.actor.enabled )
			{
				this.states.gotoAndStop(4);
				//callEvent
				if(this.onMousePress)
					this.onMousePress();
			}
		}
		private function hRelease(e:MouseEvent):void
		{
			if( this.actor.enabled )
			{
				this.states.gotoAndStop(3);
				//callEvent
				if(this.onMouseRelease)
					this.onMouseRelease();
			}
		}
		private function hKeyboard(e:KeyboardEvent):void
		{
			if(this.keys && this.keys.indexOf(e.keyCode) >= 0)
			{
				this.hRelease(null);
			}
		}
		private function updateText():void
		{
			if(this.buttonText)
			{
				try { this.states.txt.text = this.buttonText; } catch(e:Error){};
			}
		}
	}
	
}
